const express = require('express');
const cors = require('cors');
const multer = require('multer');
const axios = require('axios');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 文件上传配置
const upload = multer({ dest: 'uploads/' });

// AI提供商配置
const AI_PROVIDERS = {
  openai: {
    name: 'OpenAI',
    baseUrl: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1',
    apiKey: process.env.OPENAI_API_KEY,
    models: ['gpt-3.5-turbo', 'gpt-4', 'gpt-4-turbo-preview']
  },
  claude: {
    name: 'Claude',
    baseUrl: process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com',
    apiKey: process.env.ANTHROPIC_API_KEY,
    models: ['claude-3-haiku-20240307', 'claude-3-sonnet-20240229', 'claude-3-opus-20240229']
  },
  gemini: {
    name: 'Gemini',
    baseUrl: process.env.GEMINI_BASE_URL || 'https://generativelanguage.googleapis.com/v1beta',
    apiKey: process.env.GEMINI_API_KEY,
    models: ['gemini-pro', 'gemini-pro-vision']
  }
};

// 获取支持的AI提供商和模型
app.get('/api/providers', (req, res) => {
  const providers = Object.entries(AI_PROVIDERS).reduce((acc, [key, provider]) => {
    if (provider.apiKey) {
      acc[key] = {
        name: provider.name,
        models: provider.models
      };
    }
    return acc;
  }, {});
  res.json(providers);
});

// 统一AI生成接口
app.post('/api/generate', async (req, res) => {
  try {
    const { provider, model, prompt, type = 'text' } = req.body;

    if (!provider || !model || !prompt) {
      return res.status(400).json({ error: '缺少必要参数：provider, model, prompt' });
    }

    const aiProvider = AI_PROVIDERS[provider];
    if (!aiProvider || !aiProvider.apiKey) {
      return res.status(400).json({ error: '不支持的AI提供商或未配置API密钥' });
    }

    let response;
    
    switch (provider) {
      case 'openai':
        response = await callOpenAI(aiProvider, model, prompt, type);
        break;
      case 'claude':
        response = await callClaude(aiProvider, model, prompt, type);
        break;
      case 'gemini':
        response = await callGemini(aiProvider, model, prompt, type);
        break;
      default:
        return res.status(400).json({ error: '不支持的AI提供商' });
    }

    res.json({ success: true, data: response });
  } catch (error) {
    console.error('AI调用错误:', error);
    res.status(500).json({ 
      error: 'AI服务调用失败', 
      details: error.response?.data || error.message 
    });
  }
});

// OpenAI调用
async function callOpenAI(provider, model, prompt, type) {
  const response = await axios.post(
    `${provider.baseUrl}/chat/completions`,
    {
      model,
      messages: [{ role: 'user', content: prompt }],
      max_tokens: 2000,
      temperature: 0.7
    },
    {
      headers: {
        'Authorization': `Bearer ${provider.apiKey}`,
        'Content-Type': 'application/json'
      }
    }
  );
  
  return response.data.choices[0].message.content;
}

// Claude调用
async function callClaude(provider, model, prompt, type) {
  const response = await axios.post(
    `${provider.baseUrl}/v1/messages`,
    {
      model,
      max_tokens: 2000,
      messages: [{ role: 'user', content: prompt }]
    },
    {
      headers: {
        'x-api-key': provider.apiKey,
        'Content-Type': 'application/json',
        'anthropic-version': '2023-06-01'
      }
    }
  );
  
  return response.data.content[0].text;
}

// Gemini调用
async function callGemini(provider, model, prompt, type) {
  const response = await axios.post(
    `${provider.baseUrl}/models/${model}:generateContent?key=${provider.apiKey}`,
    {
      contents: [{
        parts: [{ text: prompt }]
      }]
    },
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  );
  
  return response.data.candidates[0].content.parts[0].text;
}

// 文件上传处理
app.post('/api/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '没有上传文件' });
  }
  
  res.json({
    success: true,
    file: {
      filename: req.file.filename,
      originalname: req.file.originalname,
      mimetype: req.file.mimetype,
      size: req.file.size
    }
  });
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

app.listen(PORT, () => {
  console.log(`LinkAI 服务器运行在端口 ${PORT}`);
  console.log(`访问 http://localhost:${PORT} 使用系统`);
});
